var express = require('express');
var router = express.Router();
var { userModel, cateModel, proModel } = require('../model/model')
// 吴世豪 购物车后端
/* 获取购物车列表 */
router.get('/goodlist', async (req, res) => {
  let goodlist = await proModel.find({ goods: 1 })
  res.send({
    code: 200,
    goodlist: goodlist
  })
});
// 点击加号商品数量加加
router.get('/add', async (req, res) => {
  let { _id } = req.query
  // console.log(_id, '1111111');
  let good = await proModel.findOne({ _id: _id })
  // console.log(good, '2');
  if (good.num < good.kucun) {
    good.num += 1
    good.kucun -= 1
    await good.save()
    res.send({
      code: 200,
      msg: '添加成功'
    })
  } else if (good.num == good.kucun) {
    res.send({
      code: 200,
      msg: '库存不足'
    })
  }

});
// 点击减号商品数量减减
router.get('/reduce', async (req, res) => {
  let { _id } = req.query
  // console.log(_id, '1111111');
  let good = await proModel.findOne({ _id: _id })
  // console.log(good, '2');
  if (good.num > 1) {
    good.num -= 1
    good.kucun += 1
    await good.save()
    res.send({
      code: 200,
      msg: '减少成功'
    })
  } else {
    res.send({
      code: 200,
      msg: '最少选择1件商品'
    })
  }
});
// 改变复选框的值
router.post('/change', async (req, res) => {
  let { _id } = req.query
  // console.log(_id, '1111111');
  let good = await proModel.findOne({ _id: _id })
  // console.log(good, '2');
  if (good.isChecked == true) {
    await proModel.updateOne({ _id: _id }, { $set: { isChecked: false } })
    res.send({
      code: 200,
      msg: '修改成功'
    })
  } else {
    await proModel.updateOne({ _id: _id }, { $set: { isChecked: true } })

    res.send({
      code: 200,
      msg: '修改成功'
    })
  }
});
router.post('/checkAll', async (req, res) => {
  const { isChecked } = req.body; // 此处接收新的选中状态
  await proModel.updateMany({ goods: 1 }, { isChecked: isChecked });
  res.send({
    code: 200,
    msg: '修改成功'
  });
});
// 点击结算按钮
// 点击结算按钮
router.get('/submit', async (req, res) => {
  let { ids } = req.query; // 修改为 ids
  console.log(ids, '传递的 IDs');
  // 将 ids 字符串拆分为数组
  let idArray = ids ? ids.split(',') : [];
  let Orderlist = await proModel.find({ _id: { $in: idArray } });
  console.log(Orderlist, '订单列表');
  res.send({
    code: 200,
    Orderlist: Orderlist
  });
});


let AlipaySdk = require('alipay-sdk').default;
let AlipaySdkForm = require('alipay-sdk/lib/form').default;
router.post('/alipay', async (req, res) => {
  // 从请求中获取支付的金额 // 从请求中获取订单 ID
  const { totalAmount, ids,totalName } = req.body;
  const idArray = ids.split(','); // 将 IDs 字符串转为数组

  // 实例化客户端
  const alipaySdk = new AlipaySdk({
    // 设置应用 ID
    appId: '9021000142640237',
    // 支付网关
    gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do',
    // 设置应用私钥
    privateKey: "MIIEowIBAAKCAQEAn5qjWQyuvToLQZxf6fzpsNs++fvthCDzh0yS69bKX/+my9nvfPSlME3S5fVt1GpsN1LixqG0ybi4YCG5bzA6zOKBEisrv45UvtsNfd3UJxBj3UxuJYzopYdKU6sUzuctK6IDWQg78kNE7Re1Cg48denScffgHMV/yYbD6es7OXAE47k0pcmXwmr4YrcOtM4D8DAML6yRevwaMk9imyJXKYnWKa9Pu54rqIoPLw0XU2LFYXwoMGuSAJ5IBewBgikh7BDr91QoldfbK02d+b6drzx6113zkfVXsBDhU6v5qysSSqzRxk6srlwT4BhWB4uQlphkTaVVUVIASHSCMAOFFwIDAQABAoIBABMmI4kQm3p6l1Uk5OEXBhbBB1pI3qNmrLFD/7CqEZfY/XMhz7kHRTZ5b99FRgshRaCRokHArwcw0XY/NZdgiv2AA4phgZs3AXXwpDrAva5+Ke0oOWLp+BO8Gq/VK+bzF5lPk+U/tqmHZqKnoIH3WUuwZR5lZg8tpvpP3/uVzIJEfJJiO2SwaMogvYoDzIxk3GGpoHNaM7GvAP/M7pwkAUa2zq3W6hNwUOLv+MyuLzhVznDPOsXRrIFzwl35GiaO+BfOaol+u5JxgVROJjbJh0dvkQW2rK9FM6j6ejUwQ+zLAX1YMcmJ+zwfHR8NRt1t6tHpWZvJrl5eMjneZDoisukCgYEA4iGIFnY8mpu5XMG3B9pJ06h0DpEq0cyyxlmEjoRIAGAA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pGzqAxYg6bvrf4876od41NIEFAkWkFKLH9qbRaCfDieHoIDkrq6emOCsiUcxzmkd2GHCKGCkULuQLAYRnop7TJsvZLWZ7ENRiyhxeUlmmbmEYGUjKqlpjn7OQvCcEpx3jNGBYh52ttl5diR+LbzEZIAxoQqmKUzCmIkDQIDAQAB",
    // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
    signType: 'RSA2',
    // 设置网关地址，默认是 https://openapi.alipay.com
    // endpoint: 'https://openapi.alipay.com',
  });
  let formData = new AlipaySdkForm();
  formData.addField('returnUrl', 'http://localhost:3001/list#/Orders')
  formData.addField('bizContent', {
    outTradeNo: Date.now(),
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount: totalAmount.toString(),//支付金额
    subject: totalName,
    body: '商品详情',
  });
  try {
    const result = await alipaySdk.exec(
      'alipay.trade.wap.pay',
      {},
      { formData: formData },
    );

    // console.log(result, 'result');

    // 完成支付后，更新支付状态
    // 假设支付状态存储在某个模型中，比如 orderModel

    await proModel.updateMany({ _id: { $in: idArray } }, { status: 1 });
    await proModel.updateMany({ _id: { $in: idArray } }, { goods: 2 });
    await proModel.updateMany({ _id: { $in: idArray } }, { isChecked: false });
    // console.log(_id, '订单ID');


    res.send(result);
  } catch (error) {
    console.error(error);
    res.status(500).send({ code: 500, msg: '支付失败', error });
  }
})
// 删除商品
router.get('/delete', async (req, res) => {
  let { _id } = req.query
  console.log(_id);
  
  await proModel.updateOne({ _id: _id }, { $set: { goods: 0 } })
  res.send({
    code: 200,
    msg: '删除成功'
  })
})
module.exports = router;